<template>
  <TableView class="table">
    <template #form>
      <NSpace justify="space-between">
        <NSpace align="center">
          进馆事由：
          <NInput style="width: 200rem" placeholder="请输入理由" v-model:value="paginationReactive.title" clearable />
          <NButton type="primary" style="width: 78rem" ghost
            @click="() => ((paginationReactive.page = 1), getAllInOutList())">
            查询
          </NButton>
        </NSpace>
        <NSpace align="end">
          <NButton type="primary" style="width: 115px" @click="handleExportAll" ghost :loading="exportAllLoading">
            导出
          </NButton>
        </NSpace>
      </NSpace>
    </template>

    <template #table="props">
      <NDataTable v-bind="props" :bordered="false" :columns="columns" :data="tableData" :pagination="false"
        :loading="tableLoading" />
    </template>

    <template #pagination>
      <NPagination :page-sizes="paginationReactive.pageSizes" :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page" :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange" @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker show-quick-jumper :suffix="() => '页'">
        <template #prefix>
          <span style="font-size: 14px;"> 共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>
</template>

<script setup lang="ts">
import { NSpace, NInput, NButton, NDataTable, NPagination, useMessage } from 'naive-ui'
import { h, onDeactivated, reactive, ref, watch } from 'vue'
import { useViewerStore } from '../Common/store'
import { sendRequest } from '@/utils/api'
import { useRoute } from 'vue-router'
import { type DataTableColumns } from 'naive-ui'
import TableView from '@/components/TableView.vue'
import router from '@/router'
const message = useMessage()
const useStore = useViewerStore()
const route = useRoute()
import { RecordType } from '@/router/utils'

const columns: DataTableColumns = [
  {
    title: '申请人',
    key: 'userName',
    width: 60,
    align: useStore.isCenter
  },
  {
    title: '申请人部门',
    key: 'deptName',
    width: 100,
    align: useStore.isCenter
  },
  {
    title: '进馆事由',
    key: 'reasons',
    width: 100,
    align: useStore.isCenter,
    ellipsis: {
      tooltip: {
        contentStyle: {
          maxWidth: '400rem'
        }
      }
    }
  },
  {
    title: '人员入库类型',
    key: 'passType',
    width: 60,
    align: useStore.isCenter
  },
  {
    title: '出入区域',
    key: 'region',
    width: 100,
    align: useStore.isCenter,
    ellipsis: {
      tooltip: {
        contentStyle: {
          maxWidth: '400px'
        }
      }
    }
  },
  {
    title: '是否进入山体库',
    key: 'massifFlag',
    width: 80,
    align: useStore.isCenter,
    render: (e: any) => {
      return e.massifFlag == 0 ? '否' : '是'
    }
  },
  {
    title: '山体库陪同人员',
    key: 'followUserName',
    width: 80,
    align: useStore.isCenter
  },
  {
    title: '人员入库有效期',
    key: 'endTime',
    width: 160,
    align: useStore.isCenter,
    render: (e: any) => {
      return e.startTime + ' ~ ' + e.endTime
    }
  },
  {
    title: '状态',
    key: 'fromStatus',
    width: 60,
    align: useStore.isCenter
  },
  {
    title: '操作',
    key: 'action',
    align: 'center',
    width: 150,
    fixed: 'right',
    render: (row: any) => [
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => {
            RecordType.setRouteNameTypeFalse('A0581')
            router.push({ path: '/OA/PersonnelInStorage/InOutDetail', query: { id: row.id } })
          }
        },
        {
          default: () => '详情'
        }
      ),
      h(
        NButton,
        {
          type: 'info',
          loading: exportLoading.value,
          quaternary: true,
          style: {
            display: row.fromStatusCode == 'A0605' ? 'inline-flex' : 'none'
          },
          onClick: () => handleExport(row)
        },
        {
          default: () => '导出'
        }
      )
    ]
  }
]

//导出
function download(headers: any, data: any, name?: string) {
  const val = headers['content-disposition']?.match(/(?<=filename=)(.*)/)
  let filename = val ? decodeURIComponent(val[0]) : name + '导出.pdf'
  const a = document.createElement('a')
  let binaryData = []
  binaryData.push(data)
  a.href = window.URL.createObjectURL(new Blob(binaryData))
  a.download = filename
  a.click()
  window.URL.revokeObjectURL(a.href)
}


//全部导出
const exportAllLoading = ref(false)
async function handleExportAll() {
  exportAllLoading.value = true
  const [error, data, headers] = await sendRequest({
    module: 'inStorage',
    api: 'inoutAllExport',
    override: {
      params: {
        page: 1,
        limit: 99999,
        ...FormData
      }
    }
  })
  if (error) return message.error(error.message)
  download(headers, data, '全馆人员入库统计')
  exportAllLoading.value = false
}

//单个导出
const exportLoading = ref(false)
async function handleExport(val: any) {
  exportLoading.value = true
  const [error, data, headers] = await sendRequest({
    module: 'inStorage',
    api: 'inoutDepOneExport',
    override: {
      params: {
        passId: val?.id
      }
    }
  })
  if (error) return message.error(error.message)
  download(headers, data, '全馆人员入库统计')
  exportLoading.value = false
}

const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  title: null, //标题字段
  onChange: (page: number) => {
    paginationReactive.page = page
    getAllInOutList()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    getAllInOutList()
  }
})
// 获取列表
const tableData = ref()
const tableLoading = ref(false)
const getAllInOutList = async () => {
  tableLoading.value = true
  const [error, res] = await sendRequest({
    module: 'inStorage',
    api: 'totalList',
    override: {
      params: {
        page: paginationReactive.page,
        limit: paginationReactive.pageSize,
        reasons: paginationReactive.title
      }
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  tableData.value = []
  setTimeout(() => {
    tableData.value = res.data.list
    paginationReactive.itemCount = res.data.totalCount
  }, 0)
}

const keyUpDown = (e: any) => e.key == 'Enter' && (paginationReactive.page = 1,getAllInOutList())
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))

watch(
  () => route,
  async () => {
    if (route.path == '/OA/PersonnelInStorage/totalInout') {
      getAllInOutList()
      window.addEventListener('keyup', keyUpDown, false)  // 回车
    }
  },
  { deep: true, immediate: true }
)
</script>

<style scoped lang="scss">
.table {
  padding: 29rem 30rem 42rem;
}
</style>
